package mgr

import (
	"context"
	"gitee.com/lailonghui/vehicle-supervision-framework/pkg/asserts"
	"gitee.com/lailonghui/vehicle-supervision-framework/pkg/auths"
	"gitee.com/lailonghui/vehicle-supervision-framework/pkg/beans"
	"gitee.com/lailonghui/vehicle-supervision-framework/pkg/gins/middleware"
	"gitee.com/lailonghui/vehicle-supervision-framework/pkg/graphqls"
	"gitee.com/lailonghui/vehicle-supervision-framework/pkg/graphqls/directive"
	"gitee.com/shiqiyue/xd-bi/internal/pkg/instance"
	"github.com/99designs/gqlgen/graphql/handler"
	"github.com/gin-gonic/gin"
)

func NewGqlHandler() gin.HandlerFunc {
	r := &Resolver{}

	err := beans.ProvideBean(r)
	asserts.Nil(err, err)
	err = beans.Populate()
	asserts.Nil(err, err)

	c := Config{
		Resolvers: r,
	}
	c.Directives.Validate = directive.Validate
	srv := handler.NewDefaultServer(NewExecutableSchema(c))
	graphqls.CommonMiddle(srv)
	srv.AroundResponses(auths.GqlgenRbacAuthMiddle(instance.GetAuthViper(), func(c context.Context) (*gin.Context, error) {
		return middleware.GinContextFromContext(c)
	}))
	return func(c *gin.Context) {
		srv.ServeHTTP(c.Writer, c.Request)
	}
}
